
package com.cuit.service.Book;

import com.cuit.mapper.Book.BookUserMapper;
import com.cuit.pojo.BookUser;
import com.google.common.collect.Lists;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class GuessLikeService {
    @Resource
    private BookUserMapper bookUserMapper;

    //使用redis
    @Resource
    RedisTemplate<String,String> rt;

    //往redius里方id,每点击一次加1
    public void increase(Integer id,String username) {
        Jedis jedis =new Jedis("127.0.0.1");
        jedis.zincrby(username,1.0D,id+"");
        //保留书本信息
        jedis.zremrangeByRank(username,0,-21);
        jedis.close();
    }
    //取出存入的id
    public List<Long> getLikeBookId(String username){
        Jedis jedis = new Jedis("127.0.0.1");
        Set<String> idSet = jedis.zrevrange(username, 0, -1);
        List<Long> ids = idSet.stream().map(Long::parseLong).collect(Collectors.toList());
        return  ids;
    }
    //得到喜欢的书本信息
    public  List<BookUser> getLikeBook(String username){
        List<Long> ids = getLikeBookId(username);
        if(ids.isEmpty()){
            return  Lists.newArrayList();
        }
        List<BookUser> bookUserList = bookUserMapper.selectBatchIds(ids);
        return bookUserList;
    }
    //存入bookid
    public void setBookid(Integer id) {
//        Jedis jedis = new Jedis( "47.109.38.52");
        ValueOperations<String, String> forValue = rt.opsForValue();
//        jedis.set("bookId", id + "");
        forValue.set("bookId", String.valueOf(id));
        //设置过期时间
        rt.expire("bookId",60*60*1000, TimeUnit.MILLISECONDS);

    }
    public Integer getBookId(){
//        Jedis jedis = new Jedis(" 47.109.38.52");
//        String bookId = jedis.get("bookId");
        ValueOperations<String, String> forValue = rt.opsForValue();
        String bookId = forValue.get("bookId");
        return  Integer.valueOf(bookId);
    }
}
